package com.example.tourpal.model;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.example.tourpal.R;
import com.example.tourpal.util.Tools;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class UserDataManager {
	private static final String TAG = "chengongguo/UserDataManager";
	public static final String DATA_REGISTER = LocalDataLoaderHelp.BASE_IP_URL+"/lyb/api/v1/user/register/";
	public static final String DATA_LOGIN = LocalDataLoaderHelp.BASE_IP_URL+"/lyb/api/v1/user/login/";
	public static final int REGISTER_START = 1;
	public static final int LOGIN_START = 2;
	public static final int FINDPASSWORD_START = 3;
	public static final int REGISTER_OK = 4;
	public static final int LOGIN_OK = 5;
	public static final int FINDPASSWORD_OK = 6;
	public static final int REGISTER_ERROR = 7;
	public static final int LOGIN_ERROR = 8;
	public static final int FINDPASSWORD_ERROR = 9;
	private Context mContext;
	private Tools mTools;
	private ProgressDialog progressDialog = null;

	private RegisterLishenter mRegisterLishenter = null;

	public interface RegisterLishenter {
		public void onRegister();
	}

	private UserDataLishenter mUserDataLishenter = null;

	public interface UserDataLishenter {
		public void requestUserData(User user);
	}

	public UserDataManager(Context context) {
		mContext = context;
		mTools = new Tools(context, TAG);
		initContentView();
	}

	private void initContentView() {
		progressDialog = new ProgressDialog(mContext);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setCancelable(true);
		progressDialog.setCanceledOnTouchOutside(false);
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REGISTER_START:
				progressDialog.setMessage(mContext.getResources().getString(
						R.string.user_register_waiting));
				progressDialog.show();
				break;
			case REGISTER_OK:
				mTools.showToast(R.string.user_register_sucess);
				progressDialog.dismiss();
				break;
			case REGISTER_ERROR:
				Bundle bundle = msg.getData();
				String error = bundle.getString("error");
				mTools.showToast(error);
				progressDialog.dismiss();
				break;
			case LOGIN_START:
				progressDialog.setMessage(mContext.getResources().getString(
						R.string.user_login_waiting));
				progressDialog.show();
				break;
			case LOGIN_OK:
				mTools.showToast(R.string.user_login_sucess);
				progressDialog.dismiss();
				break;
			case LOGIN_ERROR:
				mTools.showToast(R.string.user_login_fail);
				progressDialog.dismiss();
				break;
			case FINDPASSWORD_START:
				progressDialog.setMessage(mContext.getResources().getString(
						R.string.user_find_password_waiting));
				progressDialog.show();
				break;
			case FINDPASSWORD_OK:
				mTools.showToast(R.string.user_find_password_sucess);
				progressDialog.dismiss();
				break;
			case FINDPASSWORD_ERROR:
				mTools.showToast(R.string.user_find_password_fail);
				progressDialog.dismiss();
				break;
			}
		}
	};

	public static String getData(String jsonObject, String url) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);
		StringBuilder sb = new StringBuilder();
		try {
			Log.i(TAG, "json=" + jsonObject);
			List<NameValuePair> nvs = new ArrayList<NameValuePair>();
			nvs.add(new BasicNameValuePair("json", jsonObject));
			httpost.setEntity(new UrlEncodedFormEntity(nvs, HTTP.UTF_8));
			HttpResponse response = httpclient.execute(httpost);
			HttpEntity entity = response.getEntity();
			int status = response.getStatusLine().getStatusCode();
			Tools.Log("status=" + status);
			if (status != HttpStatus.SC_OK || entity == null) {
				return null;
			}
			InputStreamReader isr = new InputStreamReader(entity.getContent());
			BufferedReader bufReader = new BufferedReader(isr);
			String lineText = null;
			while ((lineText = bufReader.readLine()) != null) {
				sb.append(lineText);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		return sb.toString();
	}

	private int checkJsonObjectState(String json) {
		Tools.Log("json=" + json);
		if(json == null || TextUtils.isEmpty(json)){
			return -1;
		}
		int status = new JsonParser().parse(json).getAsJsonObject()
				.get("status").getAsInt();
		if (status != 0) {
			String message = new JsonParser().parse(json).getAsJsonObject()
					.get("message").getAsString();
			Message msg = new Message();
			Bundle bundle = new Bundle();
			bundle.putString("error", message);
			msg.setData(bundle);
			msg.what = REGISTER_ERROR;
			mHandler.sendMessage(msg);
		}
		return status;
	}

	private User parseUserJSON2Obj(String json) {
		User user = User.getDefaultUser();
		JsonElement element = new JsonParser().parse(json).getAsJsonObject()
				.get("result");
		Gson gson = new Gson();
		user = gson.fromJson(element, User.class);
		return user;
	}

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivity = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						Log.i("NetWorkState", "Availabel");
						return true;
					}
				}
			}
		}
		mTools.showToast(R.string.network_not_ok);
		Log.i("NetWorkState", "Unavailabel");
		return false;
	}

	public void register(final User user, RegisterLishenter registerLishenter) {
		mRegisterLishenter = registerLishenter;
		mHandler.sendEmptyMessage(REGISTER_START);
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (!isNetworkAvailable())
					return;
				String json = null;
				try {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("email", user.getEmail());
					jsonObject.put("userName", user.getUserName());
					jsonObject.put("password", user.getPassword());
					jsonObject.put("sex", user.getSex());
					json = getData(jsonObject.toString(), DATA_REGISTER);
				} catch (Exception e) {
					Log.e(TAG, e.toString());
				}
				if (checkJsonObjectState(json) == 0) {
					mHandler.sendEmptyMessage(REGISTER_OK);
					mRegisterLishenter.onRegister();
				}
			}
		}).start();
	}

	public void login(final User user, UserDataLishenter userDataLishenter) {
		mUserDataLishenter = userDataLishenter;
		mHandler.sendEmptyMessage(LOGIN_START);
		new Thread() {
			@Override
			public void run() {
				if (!isNetworkAvailable())
					return;
				String json = null;
				try {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("email", user.getEmail());
					jsonObject.put("password", user.getPassword());
					json = getData(jsonObject.toString(), DATA_LOGIN);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				if (checkJsonObjectState(json) == 0) {
					User user2 = parseUserJSON2Obj(json);
					mUserDataLishenter.requestUserData(user2);
					mHandler.sendEmptyMessage(LOGIN_OK);
				} else{
					mHandler.sendEmptyMessage(LOGIN_ERROR);
				}
			}
		}.start();
	}

	public void findPassword(final User user,
			UserDataLishenter userDataLishenter) {
		mUserDataLishenter = userDataLishenter;
		mHandler.sendEmptyMessage(FINDPASSWORD_START);
		new Thread() {
			@Override
			public void run() {
				if (!isNetworkAvailable())
					return;
				Map<String, String> params = new HashMap<String, String>();
				params.put("email", user.getEmail());
				String json = null;
				try {
					//http: // 222.73.205.208:8080/lyb/api/v1/user/login?json={"email":"hanfeng@qq.com","password":"123456"}
					json = ServiceDataLoader.sendGetRequest(DATA_LOGIN, params);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				if (json == null || json.length() == 0) {
					mHandler.sendEmptyMessage(FINDPASSWORD_ERROR);
					return;
				}
				User user;
				try {
					user = parseUserJSON2Obj(json);
				} catch (Exception e) {
					mHandler.sendEmptyMessage(FINDPASSWORD_ERROR);
					return;
				}
				mUserDataLishenter.requestUserData(user);
				mHandler.sendEmptyMessage(FINDPASSWORD_OK);
			}
		}.start();

	}

}
